/**
 * Todo任务完成工作流程
 * 主要编排脚本，整合所有工具实现完整的任务完成流程
 */

const todoParser = require('./todo-parser');
const testRunner = require('./test-runner');
const gitHelper = require('./git-helper');
const attemptTracker = require('./attempt-tracker');

/**
 * 执行完整的任务完成工作流程
 * @param {Object} options 配置选项
 * @returns {Object} 执行结果
 */
async function executeTaskCompletion(options = {}) {
    const {
        autoApprove = false,        // 是否自动批准任务
        maxAttempts = 3,           // 最大尝试次数
        verbose = true,             // 详细输出
        commitOnSuccess = true      // 成功时是否自动提交
    } = options;

    console.log('🚀 开始Todo任务完成工作流程');
    console.log('='.repeat(40));

    try {
        // 步骤1: 获取下一个高优先级任务
        const nextTask = todoParser.getNextHighPriorityTask();
        if (!nextTask) {
            return {
                success: true,
                message: '✅ 所有任务已完成！',
                status: 'all_completed'
            };
        }

        console.log(`📋 当前任务: ${nextTask.content}`);
        console.log(`📊 优先级: ${nextTask.priority} (${nextTask.category})`);
        console.log(`📄 行号: ${nextTask.lineNumber}`);
        console.log('');

        // 步骤2: 检查任务尝试状态
        const taskAttempts = attemptTracker.getTaskAttempts(nextTask.content);
        console.log(`🔄 尝试状态: ${taskAttempts.attempts}/${maxAttempts} 次尝试`);

        if (taskAttempts.status === 'deferred') {
            console.log(`⚠️  任务已延期: ${taskAttempts.deferredReason}`);
            return {
                success: false,
                message: '任务已延期，跳过执行',
                taskId: taskAttempts.taskId,
                status: 'deferred'
            };
        }

        if (taskAttempts.attempts >= maxAttempts) {
            console.log(`❌ 已达到最大尝试次数 (${maxAttempts})`);
            return {
                success: false,
                message: '已达到最大尝试次数，需要更换实现方式或延期任务',
                taskId: taskAttempts.taskId,
                status: 'max_attempts_reached'
            };
        }

        // 步骤3: 开始新的尝试
        console.log('🎯 开始新的任务尝试...');
        const attemptResult = attemptTracker.startAttempt(nextTask.content, {
            approach: 'manual',
            maxAttempts: maxAttempts
        });

        if (!attemptResult.success) {
            console.error(`❌ 开始尝试失败: ${attemptResult.error}`);
            return attemptResult;
        }

        console.log(`📝 尝试 #${attemptResult.attemptNumber} (剩余: ${attemptResult.remainingAttempts} 次)`);
        console.log(`🔧 实现方式: ${attemptResult.approach}`);
        console.log('');

        // 步骤4: 等待用户完成任务实现
        if (!autoApprove) {
            console.log('⏳ 请实现任务功能，完成后按任意键继续...');
            await waitForUserInput();
        } else {
            console.log('🤖 自动批准模式，跳过等待实现步骤');
        }

        // 步骤5: 运行测试验证
        console.log('🧪 运行测试验证...');
        const testResult = testRunner.runTests({ verbose: false });

        console.log(`📊 测试结果: ${testResult.success ? '✅ 通过' : '❌ 失败'}`);
        console.log(`⏱️  执行时间: ${(testResult.duration / 1000).toFixed(2)}秒`);
        console.log(`📈 通过率: ${testResult.total > 0 ? ((testResult.passed / testResult.total) * 100).toFixed(2) : 0}%`);

        if (testResult.total > 0) {
            console.log(`📋 测试统计: ${testResult.passed}/${testResult.total} 通过`);
        }

        // 步骤6: 完成尝试记录
        const attemptCompleteResult = attemptTracker.completeAttempt(
            attemptResult.taskId,
            testResult.success ? 'success' : 'failure',
            {
                testResult: {
                    success: testResult.success,
                    total: testResult.total,
                    passed: testResult.passed,
                    failed: testResult.failed || 0,
                    duration: testResult.duration,
                    exitCode: testResult.exitCode
                },
                coverage: testResult.coverage
            }
        );

        if (!attemptCompleteResult.success) {
            console.error(`❌ 完成尝试记录失败: ${attemptCompleteResult.error}`);
            return attemptCompleteResult;
        }

        console.log('');
        console.log(`📝 尝试 #${attemptCompleteResult.attemptNumber} 完成: ${attemptCompleteResult.result}`);
        console.log(`📊 任务状态: ${attemptCompleteResult.taskStatus}`);
        console.log(`🔄 总尝试次数: ${attemptCompleteResult.totalAttempts}`);

        // 步骤7: 处理成功或失败的情况
        if (testResult.success) {
            console.log('🎉 任务成功完成！');

            if (commitOnSuccess) {
                console.log('💾 提交代码到Git...');
                const commitResult = gitHelper.addAndCommit(
                    `feat: 完成任务 - ${nextTask.content.substring(0, 50)}...`
                );

                if (commitResult.success) {
                    console.log(`✅ 提交成功: ${commitResult.commit?.substring(0, 8)}`);
                } else {
                    console.warn(`⚠️  提交失败: ${commitResult.error || '未知错误'}`);
                }
            }

            return {
                success: true,
                message: '任务成功完成',
                task: nextTask,
                attempt: attemptCompleteResult,
                testResult: testResult,
                status: 'completed'
            };

        } else {
            console.log('❌ 任务失败');

            if (attemptCompleteResult.remainingAttempts > 0) {
                console.log(`🔄 还剩余 ${attemptCompleteResult.remainingAttempts} 次尝试机会`);
                console.log('💡 建议: 修复测试失败后重新运行此脚本');
            } else {
                console.log('⚠️  已达到最大尝试次数');
                console.log('💡 建议: 更换实现方式或延期任务');
            }

            return {
                success: false,
                message: '任务失败',
                task: nextTask,
                attempt: attemptCompleteResult,
                testResult: testResult,
                status: 'failed',
                remainingAttempts: attemptCompleteResult.remainingAttempts
            };
        }

    } catch (error) {
        console.error('💥 工作流程执行失败:', error.message);
        return {
            success: false,
            message: `工作流程失败: ${error.message}`,
            error: error.stack,
            status: 'workflow_error'
        };
    }
}

/**
 * 等待用户输入
 * @returns {Promise<void>}
 */
function waitForUserInput() {
    return new Promise((resolve) => {
        process.stdin.setRawMode(true);
        process.stdin.resume();
        process.stdin.on('data', () => {
            process.stdin.setRawMode(false);
            process.stdin.pause();
            resolve();
        });
    });
}

/**
 * 批量执行多个任务
 * @param {number} maxTasks 最大任务数量
 * @param {Object} options 配置选项
 * @returns {Object} 批量执行结果
 */
async function executeBatch(maxTasks = 1, options = {}) {
    console.log(`🚀 开始批量执行 (最多 ${maxTasks} 个任务)`);
    console.log('='.repeat(50));

    const results = {
        total: 0,
        completed: 0,
        failed: 0,
        deferred: 0,
        tasks: []
    };

    for (let i = 0; i < maxTasks; i++) {
        console.log(`\n📋 执行第 ${i + 1}/${maxTasks} 个任务`);
        console.log('-'.repeat(30));

        const result = await executeTaskCompletion(options);
        results.total++;
        results.tasks.push(result);

        switch (result.status) {
            case 'completed':
                results.completed++;
                break;
            case 'failed':
            case 'max_attempts_reached':
                results.failed++;
                break;
            case 'deferred':
                results.deferred++;
                break;
            case 'all_completed':
                console.log('🎉 所有任务已完成！');
                return results;
        }

        // 如果任务失败且还有剩余尝试次数，询问是否继续
        if (!result.success && result.remainingAttempts > 0) {
            console.log('\n❓ 任务失败但还有尝试机会，是否继续下一个任务？(y/n)');
            // 在非自动模式下，这里可以添加用户交互逻辑
            break; // 暂时停止，让用户处理失败
        }

        // 如果不是自动模式，每个任务后暂停
        if (!options.autoApprove && i < maxTasks - 1) {
            console.log('\n⏸️  按任意键继续下一个任务...');
            await waitForUserInput();
        }
    }

    return results;
}

/**
 * 显示工作流程统计信息
 */
function showStats() {
    console.log('📊 Todo任务完成统计');
    console.log('='.repeat(30));

    // 显示任务统计
    const taskStats = todoParser.getTaskStats();
    console.log(`总任务数: ${taskStats.total}`);
    console.log(`按类别: MCP(${taskStats.byCategory.mcp}) | 应用层(${taskStats.byCategory.application}) | 配置(${taskStats.byCategory.config}) | 其他(${taskStats.byCategory.other})`);
    console.log(`按优先级: 高(${taskStats.byPriority.high}) | 中(${taskStats.byPriority.medium}) | 低(${taskStats.byPriority.low})`);
    console.log('');

    // 显示尝试统计
    const attemptStats = attemptTracker.getStats();
    console.log(`尝试统计: ${attemptStats.totalAttempts} 次尝试，${attemptStats.successfulAttempts} 次成功，${attemptStats.failedAttempts} 次失败`);
    console.log(`平均尝试次数: ${attemptStats.averageAttemptsPerTask.toFixed(2)}`);
    console.log('');

    // 显示Git状态
    const gitStatus = gitHelper.getGitStatus();
    console.log(`Git状态: ${gitStatus.isClean ? '✅ 干净' : '⚠️  有未提交更改'}`);
    console.log(`分支: ${gitStatus.branch}`);
}

// 命令行接口
async function main() {
    const args = process.argv.slice(2);
    const command = args[0] || 'help';

    switch (command) {
        case 'run':
        case 'execute':
            await executeTaskCompletion({
                autoApprove: args.includes('--auto'),
                verbose: !args.includes('--quiet')
            });
            break;

        case 'batch':
            const maxTasks = parseInt(args[1]) || 1;
            await executeBatch(maxTasks, {
                autoApprove: args.includes('--auto'),
                verbose: !args.includes('--quiet')
            });
            break;

        case 'stats':
        case 'status':
            showStats();
            break;

        case 'help':
        default:
            console.log('🔧 Todo任务完成工作流程工具');
            console.log('');
            console.log('用法:');
            console.log('  node todo-completion.js run [--auto] [--quiet]  执行单个任务');
            console.log('  node todo-completion.js batch [数量] [--auto] [--quiet]  批量执行任务');
            console.log('  node todo-completion.js stats  显示统计信息');
            console.log('  node todo-completion.js help  显示帮助信息');
            console.log('');
            console.log('选项:');
            console.log('  --auto    自动批准模式，跳过等待实现步骤');
            console.log('  --quiet   静默模式，减少输出信息');
            break;
    }
}

// 如果直接运行此脚本，执行命令行接口
if (require.main === module) {
    main().catch(error => {
        console.error('💥 脚本执行失败:', error.message);
        process.exit(1);
    });
}

module.exports = {
    executeTaskCompletion,
    executeBatch,
    showStats,
    waitForUserInput
};